<template>
  <div id="login">
    <div class="loginBox">
      <div class="loginFromBox">
        <el-form
          :model="loginForm"
          :rules="loginFormRules"
          ref="loginFormRef"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              placeholder="请输入密码"
              show-password
              v-model="loginForm.password"
            ></el-input>
          </el-form-item>
          <el-form-item class="loginBtn">
            <el-button type="primary" @click="loginUser">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
export default {
  data() {
    return {
      loginForm: {
        username: 'Ghost',
        password: '12345678'
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {},
  methods: {
    loginUser() {
      this.$refs.loginFormRef.validate(valid => {
        if (!valid) {
          this.$router.push('/login')
        } else {
          this.$http
            .post('auth/login', {
              username: this.loginForm.username,
              password: this.loginForm.password
            })
            .then(res => {
              const resData = res.data
              if (resData.code === 200) {
                // session 只在当前页面生效
                // window.cookieStorage.setItem(
                //   'Authorization',
                //   resData.data.token
                // )

                Cookies.set('Authorization', resData.data.token)
                this.$router.push('/welcome')
                return this.$message.success(resData.msg)
              }
              this.$message.success(resData.msg)
            })
            .catch(err => {
              this.$message.error(err)
            })
        }
      })
    }
  }
}
</script>

<sytle lang="less" scoped>
#login{
  height: 100%;
  background-color: #4283f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loginBox{
  height: 250px;
  width: 500px;
  border-radius: 6px;
  background-color: #eee;
  position: absolute;
  box-shadow: 0 0 10px #ddd;

  .loginFromBox {
    position: absolute;
    bottom: 0;
    width: 86%;
  }

  .loginBtn {
    display: flex;
    justify-content: flex-end;
  }
}
</sytle>
